package com.lagou.edu.service.impl;

import com.lagou.edu.dao.UserDao;
import com.lagou.edu.pojo.AuthCode;
import com.lagou.edu.pojo.Token;
import com.lagou.edu.pojo.User;
import com.lagou.edu.service.CodeFeignClient;
import com.lagou.edu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import java.util.Date;
import java.util.Optional;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private CodeFeignClient authCodeFeignClient;

    @Override
    public Long save(User user) {
        user.setCreateTime(new Date());
        User save = userDao.save(user);
        Token token = new Token();
        token.setEmail(user.getUsername());
        token.setToken(UUID.randomUUID().toString());
        authCodeFeignClient.saveToken(token);
        return save.getId();
    }

    @Override
    public User getUnique(User user) {
        Example<User> example = Example.of(user);
        Optional<User> one = userDao.findOne(example);
        if (one.isPresent()) {
            User record = one.get();;
            return record;
        } else {
            return null;
        }
    }

    @Override
    public ModelMap checkCode(AuthCode authCode) {
        ModelMap modelMap = authCodeFeignClient.checkCode(authCode);
        return modelMap;
    }

    @Override
    public String getToken(String email) {
        String token = authCodeFeignClient.getToken(new Token(email));
        if (token == null || token.length() == 0) {
            Long id = authCodeFeignClient.saveToken(new Token(email, UUID.randomUUID().toString()));
            System.out.println(id);
            token = authCodeFeignClient.getToken(new Token(email));
        }
        return token;
    }

    @Override
    public String getEmail(String token) {
        Token token1 = new Token();
        token1.setToken(token);
        String email = authCodeFeignClient.getEmail(token1);
        return email;
    }

}
